import React from 'react'
import { BaseDetailPage, http, IBaseDetailPageProps, routeUtils, UdDetail, IUdDetailItem, validators, IBaseDetailPageState, UdModal } from '@/lib'
import DetailReviewProgress from '../../component/DetailReviewProgress'
import ButtonGroup from 'antd/lib/button/button-group'
import { Button, Select, Card } from 'antd'
import TerminalTable from './terminalTable'
import './style.scss'
import apis from '@/apis/TodoList'
import { todoApproveModalOpen } from '../../component/ApproveModalHandle'
import { ETodoTabTypes } from '../../List/configOption'
import dayjs from 'dayjs'
import { hasApproveStockAuth } from '../../common'

const { Option } = Select

export default class StockCheckDetail extends BaseDetailPage<IStockCheckDetailProps, IStockCheckDetailState> {
  private taskId
  private canReview
  private isDealerStockCheck
  private isLastApprover = false // 是否最后审批人
  private detailItems: IUdDetailItem[] = [
    {
      title: '组织机构',
      dataIndex: 'brandName',
      col: { span: 8 },
    },
    {
      title: '客户名称',
      dataIndex: 'dealerName',
      col: { span: 8 },
    },
    {
      title: '盘点周期',
      dataIndex: 'inventoryBegineTime',
      col: { span: 8 },
      render: (text, model) => {
        let render = text ? dayjs(text).format('YYYY-MM-DD') : ''
        render += model.inventoryEndTime ? '~' + dayjs(model.inventoryEndTime).format('YYYY-MM-DD') : ''
        return render
      }
    },
    {
      title: '库存表凭证',
      dataIndex: 'stockCertificate',
      col: { span: 8 },
      className: 'stock-certificate',
      render: (text) => {
        const filesUrl = text ? text.split(',') : []
        return (
          <div>
            {filesUrl.map(url => (
              <div className="certificate-item">
                <img src={url} onClick={() => this.viewStockCertificate(url)} />
                <a href={url}>下载</a>
              </div>
            ))}
          </div>
        )
      }
    },
  ]
  private hasApproveAuth = hasApproveStockAuth()
  constructor(props) {
    super(props)
    const { taskId, businessKey, type, brandCode, stockType } = routeUtils.searchStringToObject(this.props.history.location.search, { taskId: '',businessKey: '', type: '', brandCode: '', stockType: '' })
    this.taskId = taskId
    console.log(stockType)
    this.isDealerStockCheck = stockType === ETodoTabTypes.JXSSTOCKAPPROVAL
    this.canReview = type == 1 // 待处理进入才可操作审批
    // 经销商盘点详情、员工盘点详情
    const url = this.isDealerStockCheck ? apis.DealerStockCheckDetail : apis.StockCheckDetail
    this.state = {
      title: '库存盘点',
      queryAction: () => {
        return http.get(url, {
          params: {
            id: this.props.match.params.id,
            businessKey,
            brandCode,
          }
        })
      },
      ApproverList: [],
    }
  }

  componentDidMount() {
    super.componentDidMount()
    this.canReview && this.getNextApprover()
  }

  render() {
    const { dataSource } = this.state
    const processDetail = dataSource?.processDetailResult
    const tableData = dataSource?.checkStockDetails
    return super.render({
      body: (
        <>
          <Card title='任务详情' size="small">
            <UdDetail items={this.detailItems} dataSource={dataSource} />
            <TerminalTable dataSource={tableData} />
          </Card>
          <DetailReviewProgress processDetail={processDetail} />
        </>
      ),
      footer: (
        <ButtonGroup>
          {(this.canReview && this.hasApproveAuth) && <Button type="primary" onClick={this.reviewHandle}>审批</Button>}
        </ButtonGroup>
      )
    })
  }

  public reviewHandle = () => {
    const { dataSource } = this.state
    const taskId = this.taskId
    const successSubmit = () => {
      this.props.history.goBack()
    }
    const data = { taskId, roles: dataSource.roles }
    const modalItems = !this.isLastApprover ? [
      {id: 'approveUserIds', label: '下一审批人', rules: [validators.required], render: () => {
        return (
          <Select mode="multiple" showSearch={true} optionFilterProp="children">
            {this.state.ApproverList.map(item => (
              <Option key={item.value} value={item.value}>
                {item.title}
              </Option>
            ))}
          </Select>
        )
      }}
    ] : []
    const approveBeforeHandle = (params) => {
      // 将选择的审批人参数处理
      params.workflowReqVos = {
        name: 'candidateUsers', // name传固定值
        userId: params.approveUserIds,
      }
      delete params.approveUserIds
    }
    todoApproveModalOpen({ data, successSubmit, modalItems, approveBeforeHandle, passUrl: apis.StockCheckApprovePass })
  }

  public getNextApprover = async () => {
    let url = this.isDealerStockCheck ? apis.DealerNextApproverRoleList : apis.NextApproverRoleList
    try {
      const approverRoles = await http.get(url, {params: {taskId: this.taskId}})
      if (approverRoles.data && approverRoles.data[0] && approverRoles.data[0]?.roleIds?.length > 0) {
        // 有下一级审批人才去选择，用于判断是否最后审批人
        const params = {ids: approverRoles.data[0].roleIds}
        const nextApprover = await http.post(apis.NextApproverList, params)
        const ApproverList = nextApprover.data.map(({id: value, realName: title}) => ({value, title}))
        this.setState({
          ApproverList,
        })
      } else {
        this.isLastApprover = true
      }
    } catch (error) {
      
    }
  }

  public viewStockCertificate = (src) => {
    UdModal.open({
      // title: '凭证',
      content: <img style={{width: '100%', height: '100%'}} src={src} alt="库存凭证"/>,
      footer: null,
    })
  }

}

interface IStockCheckDetailProps extends IBaseDetailPageProps<{
  id: string
}> {

}

interface IStockCheckDetailState extends IBaseDetailPageState {
  ApproverList: any[]
}
